import re
from typing import List

from bs4 import BeautifulSoup, Tag

from axiom_boot.logging.setup import get_logger
from axiom_boot.scraper.interfaces import Extractor, Response, Item, Target
from src.scraper.models.SupplierItem import SupplierItem

logger = get_logger(__name__)


class AboutUsExtractor(Extractor):
    def extract(self, response: Response, target: Target) -> List[Item]:
        soup = BeautifulSoup(response.text, "html.parser")
        item: SupplierItem = target.metadata.get("item", SupplierItem())

        logger.info(f"开始从公司简介页面 {response.url} 提取详细信息...")

        # --- 基于截图和HTML文件进行最终、精确的提取 ---
        
        # General Information
        item.business_type = self._get_value_by_label(soup, "Business Type:")
        item.main_products = self._get_value_by_label(soup, "Main Products:")
        item.year_of_establishment = self._get_value_by_label(soup, "Year of Establishment:")
        item.number_of_employees = self._get_value_by_label(soup, "Number of Employees:")
        item.repeat_buyers_choice = self._get_value_by_label(soup, "Repeat Buyers Choice:")
        item.address = self._get_value_by_label(soup, "Address:")
        item.plant_area = self._get_value_by_label(soup, "Plant Area:")
        item.registered_capital = self._get_value_by_label(soup, "Registered Capital:")

        # Trade Capacity
        item.main_markets = self._get_value_by_label(soup, "Main Markets:")
        item.number_of_foreign_trading_staff = self._get_value_by_label(soup, "Number of Foreign Trading Staff:")
        item.incoterms = self._get_value_by_label(soup, "International Commercial Terms(Incoterms):")
        item.terms_of_payment = self._get_value_by_label(soup, "Terms of Payment:")
        item.average_lead_time = self._get_value_by_label(soup, "Average Lead Time:")
        item.export_year = self._get_value_by_label(soup, "Export Year:")
        item.nearest_port = self._get_value_by_label(soup, "Nearest Port:")
        
        # Production Capacity
        item.production_lines = self._get_value_by_label(soup, "Production Lines:")

        # R&D Capacity
        oem_text = self._get_value_by_label(soup, "OEM Service Available:")
        item.oem_service_available = "yes" in oem_text.lower() if oem_text else False
        
        odm_text = self._get_value_by_label(soup, "ODM Service Available:")
        item.odm_service_available = "yes" in odm_text.lower() if odm_text else False
        
        item.r_and_d_engineers = self._get_value_by_label(soup, "R&D Engineers:")
        item.production_machines = self._get_value_by_label(soup, "Production Machines:")

        logger.info(f"公司简介页面 {response.url} 提取完成。")
        return [item]

    def _get_value_by_label(self, soup: BeautifulSoup, label: str) -> str:
        """
        专门为 huazhiguan 和类似模板设计的提取器。
        它查找包含指定标签文本的 `.sr-comProfile-label` 元素，
        然后返回其相邻兄弟 `.sr-comProfile-fields` 元素中的文本。
        """
        clean_label = label.lower().strip().rstrip(":")
        
        # 查找所有可能的标签元素
        label_elements = soup.find_all(class_="sr-comProfile-label")
        
        for label_element in label_elements:
            if clean_label in label_element.get_text(strip=True).lower():
                value_element = label_element.find_next_sibling(class_="sr-comProfile-fields")
                if value_element:
                    # 特殊处理 "Main Products"
                    if clean_label == "main products:":
                        links = value_element.find_all('a')
                        if links:
                            return ", ".join([link.get_text(strip=True) for link in links if link.get_text(strip=True)])
                    
                    # 默认返回清理后的文本
                    return value_element.get_text(strip=True)
        
        # 增加一个备用策略，用于处理 Company Profile 表格布局
        table_label_cell = soup.find("td", class_="info-label-td", 
                                      string=lambda t: t and clean_label in t.strip().lower())
        if table_label_cell:
            value_cell = table_label_cell.find_next_sibling("td")
            if value_cell:
                return value_cell.get_text(strip=True)
                
        logger.warning(f"未能为标签 '{label}' 找到对应的值。")
        return "" 